package tools

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const SPLIT_CHAR = "|"

func IdStrDecodeString(str string) []string {
	return strings.Split(str, SPLIT_CHAR)
}
func IdStrEncodeString(strs []string) string {
	return strings.Join(strs, SPLIT_CHAR)
}
func IdStrEncodeInt(data []int) string {
	strs := make([]string, 0)
	for _, i := range data {
		strs = append(strs, strconv.Itoa(i))
	}
	return IdStrEncodeString(strs)
}
func IdStrDecodeInt(str string) []int {
	data := make([]int, 0)
	for _, s := range IdStrDecodeString(str) {
		if s == "" {
			continue
		} else if i, err := strconv.Atoi(s); err != nil {
			fmt.Println("E decode string to int", err.Error())
			continue
		} else {
			data = append(data, i)
		}
	}
	return data
}
func IdStrInsertIdStr(joinStr, id string) (result string, cnt int, err error) {
	db := make([]string, 0)
	for _, ele := range IdStrDecodeString(joinStr) {
		if id == ele {
			return joinStr, len(IdStrDecodeString(joinStr)), errors.New("id already existed")
		} else if ele != "" {
			db = append(db, ele)
		}
	}

	db = append(db, id)
	cnt = len(db)
	return IdStrEncodeString(db), cnt, nil
}

func IdStrRemoveIdStr(idstr, id string) (idstrNew string, cnt int, err error) {
	db := make([]string, 0)
	for _, ele := range IdStrDecodeString(idstr) {
		if id != ele {
			db = append(db, ele)
		}
	}

	if len(db) == 1 && db[0] == "" {
		return "", 0, nil
	} else {
		return IdStrEncodeString(db), len(db), nil
	}
}

func IdStrInsertIdInt(joinStr string, id int) (result string, err error) {
	db := make([]int, 0)
	for _, ele := range IdStrDecodeInt(joinStr) {
		if id == ele {
			return joinStr, errors.New("id already existed")
		}
		db = append(db, ele)
	}

	db = append(db, id)
	return IdStrEncodeInt(db), nil
}
func IdStrCheckId(idStr, id string) bool {
	return strings.Contains(idStr, id)
}
